package controllers

import (
	"encoding/json"
	"io"
	"log"
	"net/http"
	"xmgl/models"

	"github.com/astaxie/beego"
	//"strconv"
)

type SbglController struct {
	beego.Controller
}

//api,
type FjsbsController struct {
	beego.Controller
}

//api,房间的设备的配置信息
type FjsbPzxxController struct { //房间的设备的配置信息
	beego.Controller
}

func (this *SbglController) Get() {
	var (
		menu models.Menu_gl
		user models.Sut_user
	)

	if this.GetSession("USER") == nil {
		//没有取到session值，页面跳转
		http.Redirect(this.Ctx.ResponseWriter, this.Ctx.Request, "/login", http.StatusFound)
	}

	tmp, ok := this.GetSession("USER").(models.Sut_user) //注意类型断言
	if ok {
		user = tmp
	}
	log.Println("Lyfj.go MainController Get() 从session中取出用户姓名：", user.User_name) //good

	this.Data["WEBSITE"] = "房间设备管理"
	this.Data["MENU_LEFT"] = menu.Get_left_menu()
	this.Data["MENU_RIGHT"] = menu.Get_right_menu()
	this.Data["USER_NAME"] = user.User_name

	this.Layout = "layout.html"
	this.TplName = "sbgl.html"
	this.LayoutSections = make(map[string]string)
	this.LayoutSections["HtmlHeader"] = "html_header.html"
}

//Api,/api/v1/fjsbs?fj_id=27，取得某个房间的设备列表
func (this *FjsbsController) Get() {
	var (
		fj_id int
		fjsbs []models.Sut_fjsb
		json1 []byte
		err   error
	)
	this.Ctx.Input.Bind(&fj_id, "fj_id")
	fjsbs = models.Get_fjsbs(fj_id)
	if len(fjsbs) > 0 {
		json1, err = json.MarshalIndent(fjsbs, "", "")
		if err != nil {
			return
		}
		io.WriteString(this.Ctx.ResponseWriter, string(json1[:]))
	} else {
		io.WriteString(this.Ctx.ResponseWriter, "[]")
	}
}

//Api ,/api/v1/fjsbs ，POST调用，用于添加房间的设备
func (this *FjsbsController) Post() {
	var (
		fj_id     int //房间ID
		sb_id     int //设备ID
		ajax_retu Ajax_retu
		err       error
	)
	this.Ctx.Input.Bind(&fj_id, "fj_id")
	this.Ctx.Input.Bind(&sb_id, "sb_id")
	//log.Println("收到POST数据：fj_id:", fj_id, "\t sb_id:", sb_id)
	err = models.Fjsb_add(fj_id, sb_id)
	//log.Println("func (this *FjsbsController) Post() ", "\t err.Error():", err)
	ajax_retu.Isok = true
	ajax_retu.Info = err.Error()
	/*
			 result := struct {
		        Val string
		    }{username}
		    c.Data["json"] = &result
		    c.ServeJSON()   //响应前端
	*/
	this.Data["result"] = &ajax_retu
	this.ServeJSON() //响应前端
}

func (this *FjsbPzxxController) Get() {
	var (
		fjsb_id    int
		fjsbs_pzxx []models.Sut_sb_pzxx
		json1      []byte
		err        error
	)
	this.Ctx.Input.Bind(&fjsb_id, "fjsb_id")
	fjsbs_pzxx = models.Get_fjsbs_pzxx(fjsb_id)
	if len(fjsbs_pzxx) > 0 {
		json1, err = json.MarshalIndent(fjsbs_pzxx, "", "")
		if err != nil {
			return
		}
		io.WriteString(this.Ctx.ResponseWriter, string(json1[:]))
	} else {
		io.WriteString(this.Ctx.ResponseWriter, "[]")
	}
}
